#!/usr/bin/env bash

# Copyright 2017 The Fuchsia Authors
#
# Use of this source code is governed by a MIT-style
# license that can be found in the LICENSE file or at
# https://opensource.org/licenses/MIT

set -eo pipefail

DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
MKBOOTIMG="${DIR}/../third_party/tools/android/mkbootimg"

MEMBASE=0x00000000
KERNEL_OFFSET=0x1080000
USE_LZ4=0
BOOT_PART=boot

BUILD_DIR=build-arm64
CMDLINE=

function HELP {
    echo "help:"
    echo "-b <board>     : Board to flash"
    echo "-c <cmd line>  : Extra command line options"
    echo "-m             : Add mexec option to command line"
    echo "-o <dir>       : Build directory"
    echo "-M             : RAM Start address"
    echo "-K             : Kernel offset"
    echo "-z             : Use LZ4"
    echo "-P             : Boot partition name"
    echo "-h for help"
    exit 1
}

while getopts "b:c:d:mo:M:K:P:zh" FLAG; do
    case $FLAG in
        b) BOARD="${OPTARG}";;
        c) CMDLINE+=" ${OPTARG}";;
        d) RAMDISK="${OPTARG}";;
        m) CMDLINE+=" netsvc.netboot=true";;
        o) BUILD_DIR="${OPTARG}";;
        M) MEMBASE="${OPTARG}";;
        K) KERNEL_OFFSET="${OPTARG}";;
        P) BOOT_PART="${OPTARG}";;
        z) USE_LZ4=1;;
        h) HELP;;
        \?)
            echo unrecognized option
            HELP
            ;;
    esac
done
shift $((OPTIND-1))

if [[ -z "${BOARD}" ]]; then
    echo must specify a board to flash
    HELP
fi

BOOTDATA_BIN="${BUILD_DIR}/${BOARD}-zircon-bootimage.bin"
ZBOOTDATA_BIN="${BUILD_DIR}/z${BOARD}-zircon-bootimage.bin"
OUT_IMAGE="${BUILD_DIR}/${BOARD}-boot.img"

if [[ ${USE_LZ4} == 1 ]]; then
    lz4 -c ${BOOTDATA_BIN} > ${ZBOOTDATA_BIN}
else
    gzip -c ${BOOTDATA_BIN} > ${ZBOOTDATA_BIN}
fi

$MKBOOTIMG \
--kernel "${ZBOOTDATA_BIN}" \
--kernel_offset $KERNEL_OFFSET \
--base $MEMBASE \
--cmdline "${CMDLINE}" \
-o "${OUT_IMAGE}"

fastboot flash "${BOOT_PART}" "${OUT_IMAGE}"
fastboot reboot
